package com.hltx.interceptor;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hltx.pojo.user.User;
import com.hltx.service.user.UserManager;
import com.hltx.util.CustomUtil;
import com.hltx.util.MessagesCode;
import com.hltx.util.ResultInfo;
import com.hltx.util.ResultUtil;

public class AppSecurityInterceptor extends HandlerInterceptorAdapter {

	@Value("${app.key}")
	private String key;

	@Resource(name = "userService")
	private UserManager userService;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		response.setContentType("text/html;charset=UTF-8");
		try {
			Map<String, String> paramsO = new TreeMap<String, String>();
			Map requestParams = request.getParameterMap();
			if (requestParams != null && requestParams.size() > 0) {
				for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
					String name = (String) iter.next();
					String[] values = (String[]) requestParams.get(name);
					String valueStr = "";
					for (int i = 0; i < values.length; i++) {
						valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
					}
					paramsO.put(name, valueStr);
				}
			}
			String sign = paramsO.get("sign");
			System.out.println("111111:"+paramsO);
			if (StringUtils.isNotEmpty(sign)) {
				System.out.println("111111:"+sign);
				String mySign = CustomUtil.createSign(paramsO, key);
				
				if (StringUtils.equals(sign.toUpperCase(), mySign)) {
					request.getSession().setAttribute("terminal", "app");

					// 验证是否登录
					String signLogin = request.getParameter("signLogin");
					boolean isLogin = false;
					String loginId = "";
					System.out.println("登录验证开始");
					if (StringUtils.isNotEmpty(signLogin)) {
						loginId = request.getParameter("loginId");
						String nonce = request.getParameter("nonce");
						String timestamp = request.getParameter("timestamp");
						Map<String, Object> login = userService.getLoginInfo(Integer.parseInt(loginId));
						if (login != null && !login.isEmpty()) {
							paramsO.clear();
							paramsO.put("userName", (String) login.get("userName"));
							paramsO.put("pwd", (String) login.get("pwd"));
							paramsO.put("nonce", nonce);
							paramsO.put("timestamp", timestamp);
							mySign = CustomUtil.createSign(paramsO, key);
							if (StringUtils.equals(signLogin.toUpperCase(), mySign)) {
								isLogin = true;
							}
						}

						String requestType = request.getHeader("X-Requested-With");
						if (!isLogin) {
							if (!StringUtils.equals(requestType, "XMLHttpRequest")) {
								String contextPath = request.getContextPath();
								System.out.println(contextPath);
								response.sendRedirect(contextPath + "/toLogin");
							} else {
								Map<String, Object> resMap = new HashMap<String, Object>();
								resMap.put("result",
										ResultUtil.initResult(ResultInfo.ERROR, MessagesCode.LOGIN_OUT, "用户未登录"));
								ObjectMapper om = new ObjectMapper();
								response.getWriter().print(om.writeValueAsString(resMap));
							}

						} else {
							if (!StringUtils.equals(requestType, "XMLHttpRequest")) {
								User resultUser = userService.getUserInfo(Integer.parseInt(loginId));
								if (resultUser != null) {
									request.getSession().removeAttribute("sessionUser");
									request.getSession().setAttribute("sessionUser", resultUser);
								}
							}
						}

						return isLogin;

					}

					return true;
				}

			}

			return false;
		} catch (Exception e) {

			return false;
		}
	}

}
